package com.thirteen.start.controller;

import com.thirteen.service.ExampleService;
import com.thirteen.service.dto.ExampleDTO;
import com.thirteen.start.constant.ResultCodeEnum;
import com.thirteen.start.vo.ExampleVO;
import com.thirteen.start.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hhx
 * @since 2020-8-27 23:10:16
 */
@RestController
@RequestMapping("/example")
public class ExampleController {

    @Autowired
    private ExampleService exampleService;

    @GetMapping("/list")
    public Result<List<ExampleVO>> queryExamplesByTitle(@RequestParam Long pram,
                                                        @RequestParam String keyword,
                                                        @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
                                                        @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize) {
        if (!checkAuthority(pram)) {
            return Result.createFalse(ResultCodeEnum.PermissionDenied);
        }
        List<ExampleVO> vos = new ArrayList<>();
        List<ExampleDTO> dtos = exampleService.getExamplesContains(keyword, pageNum, pageSize);
        if (!CollectionUtils.isEmpty(dtos)) {
            for (ExampleDTO dto : dtos) {
                ExampleVO vo = new ExampleVO();
                BeanUtils.copyProperties(dto, vo);
                vos.add(vo);
            }
        }
        return Result.create(vos);
    }

    @GetMapping("hello")
    public Result<String> hello() {
        return Result.create("hello!");
    }

    private boolean checkAuthority(Long pram) {
        return true;
    }
}
